package me.szlx.thing.parser;

import me.szlx.thing.*;
import me.szlx.thing.bundle.SimpleThingBundle;
import me.szlx.thing.bundle.ThingBundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public abstract class AbstractThingParser<T extends Thing> implements ThingParser<T> {
    private static final String DEFAULT_PREFIX = "me.szlx.thing.";
    private ThingCreator<T> thingCreator;
    private TraitCreator traitCreator;
    private String prefix = DEFAULT_PREFIX;
    protected Logger logger = LoggerFactory.getLogger(getClass());

    public ThingBundle<T> parse(InputStream resource) {
        if (resource == null) {
            logger.debug("资源内容为null");
            return new SimpleThingBundle<T>(null);
        }
        return new SimpleThingBundle<T>(doParse(resource));

    }

    protected abstract List<T> doParse(InputStream resourceStream);

    protected T createThing(Object code, String name, String description, Traits traits) {
        return thingCreator != null ? thingCreator.create(code, name, description, traits) : (T) Thing.create(code, name, description, traits);
    }

    protected Trait createTrait(String name, String value) {
        return traitCreator != null ? traitCreator.create(name, value) : Trait.create(name, value);
    }

    public ThingCreator<T> getThingCreator() {
        return thingCreator;
    }

    public void setThingCreator(ThingCreator<T> thingCreator) {
        this.thingCreator = thingCreator;
    }

    public TraitCreator getTraitCreator() {
        return traitCreator;
    }

    public void setTraitCreator(TraitCreator traitCreator) {
        this.traitCreator = traitCreator;
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        if (prefix != null && !prefix.endsWith(".")) {
            prefix = prefix + ".";
        }
        this.prefix = prefix;
    }
}
